//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by 伏文东 on 2018/1/25.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
//        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        
        title = "登录新浪微博"
        webView.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        guard let url = URL(string: urlString)  else {return}
        let request = URLRequest(url: url)
        
        // 加载请求
        webView.loadRequest(request)
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill() {
        // 准备 js
        let js = "document.getElementById('userId').value = '591738494@qq.com';" + "document.getElementById('passwd').value = '13649921665';"
        webView.stringByEvaluatingJavaScript(from: js)
        print("在这")
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    /// webView 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要求在家的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false {return true}
        
        if request.url?.query?.hasPrefix("code=") == false {
            close()
            return false
        }
        let code = request.url?.query?.suffix(from: "code=".endIndex) ?? ""
        print("获取授权码：\(code)")

        WBNetworkManager.shared.loadAccessToken(code: String(code)) { (isSuccess) in
            if isSuccess {
                
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification),
                    object: nil)
                
                self.close()
            } else{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}





























